<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>脚本来源管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        h1, h2 {
            color: #333;
        }
        .container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 20px;
            flex: 1;
            min-width: 300px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .loading {
            text-align: center;
            padding: 20px;
            font-style: italic;
            color: #666;
        }
        .actions {
            display: flex;
            gap: 10px;
        }
        .edit-btn {
            background-color: #2196F3;
        }
        .edit-btn:hover {
            background-color: #0b7dda;
        }
        .nav-links {
            margin-bottom: 20px;
        }
        .nav-links a {
            margin-right: 15px;
            color: #4CAF50;
            text-decoration: none;
        }
        .nav-links a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <h1>脚本来源管理</h1>
    
    <div class="nav-links">
        <a href="javascript:void(0)" onclick="navigateTo('/')">首页</a>
        <a href="javascript:void(0)" onclick="navigateTo('/stats')">统计页面</a>
        <a href="javascript:void(0)" onclick="navigateTo('/sources')">脚本来源管理</a>
    </div>
    
    <div class="container">
        <div class="card">
            <h2>添加新脚本来源</h2>
            <form id="addSourceForm">
                <div class="form-group">
                    <label for="sourceName">名称</label>
                    <input type="text" id="sourceName" name="name" required placeholder="例如: game_client_v1">
                </div>
                <div class="form-group">
                    <label for="sourceDescription">描述</label>
                    <textarea id="sourceDescription" name="description" rows="3" placeholder="描述这个脚本来源..."></textarea>
                </div>
                <button type="submit">添加</button>
            </form>
        </div>
        
        <div class="card">
            <h2>编辑脚本来源</h2>
            <form id="editSourceForm" style="display: none;">
                <input type="hidden" id="editSourceId">
                <div class="form-group">
                    <label for="editSourceName">名称</label>
                    <input type="text" id="editSourceName" disabled>
                </div>
                <div class="form-group">
                    <label for="editSourceDescription">描述</label>
                    <textarea id="editSourceDescription" name="description" rows="3"></textarea>
                </div>
                <button type="submit">保存</button>
                <button type="button" id="cancelEdit">取消</button>
            </form>
            <div id="selectSourcePrompt">
                <p>从左侧列表选择一个脚本来源进行编辑</p>
            </div>
        </div>
    </div>
    
    <div class="card">
        <h2>脚本来源列表</h2>
        <div id="sourcesList" class="loading">加载中...</div>
    </div>
    
    <script>
        // 使用相对URL，避免协议问题
        function navigateTo(path) {
            window.location.href = path;
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            // 使用相对URL
            const addSourceForm = document.getElementById('addSourceForm');
            const editSourceForm = document.getElementById('editSourceForm');
            const selectSourcePrompt = document.getElementById('selectSourcePrompt');
            const cancelEditBtn = document.getElementById('cancelEdit');
            
            // 加载脚本来源列表
            loadSources();
            
            // 添加脚本来源表单提交
            addSourceForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const name = document.getElementById('sourceName').value.trim();
                const description = document.getElementById('sourceDescription').value.trim();
                
                if (!name) {
                    alert('脚本来源名称不能为空');
                    return;
                }
                
                fetch('/api/script-sources', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ name, description })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('脚本来源添加成功');
                        addSourceForm.reset();
                        loadSources();
                    } else {
                        alert(`添加失败: ${data.message}`);
                    }
                })
                .catch(error => {
                    console.error('添加脚本来源失败:', error);
                    alert('添加脚本来源失败，请查看控制台了解详情');
                });
            });
            
            // 编辑脚本来源表单提交
            editSourceForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const id = document.getElementById('editSourceId').value;
                const description = document.getElementById('editSourceDescription').value.trim();
                
                fetch(`/api/script-sources/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ description })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('脚本来源更新成功');
                        hideEditForm();
                        loadSources();
                    } else {
                        alert(`更新失败: ${data.message}`);
                    }
                })
                .catch(error => {
                    console.error('更新脚本来源失败:', error);
                    alert('更新脚本来源失败，请查看控制台了解详情');
                });
            });
            
            // 取消编辑
            cancelEditBtn.addEventListener('click', hideEditForm);
            
            // 加载脚本来源列表
            function loadSources() {
                document.getElementById('sourcesList').innerHTML = '<div class="loading">加载中...</div>';
                
                fetch('/api/script-sources')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            renderSourcesList(data.sources);
                        } else {
                            document.getElementById('sourcesList').innerHTML = '<div>加载失败</div>';
                        }
                    })
                    .catch(error => {
                        console.error('加载脚本来源失败:', error);
                        document.getElementById('sourcesList').innerHTML = '<div>加载失败</div>';
                    });
            }
            
            // 渲染脚本来源列表
            function renderSourcesList(sources) {
                if (!sources || sources.length === 0) {
                    document.getElementById('sourcesList').innerHTML = '<div>暂无脚本来源</div>';
                    return;
                }
                
                let html = `
                    <table>
                        <thead>
                            <tr>
                                <th>名称</th>
                                <th>描述</th>
                                <th>事件数量</th>
                                <th>创建时间</th>
                                <th>更新时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                sources.forEach(source => {
                    html += `
                        <tr>
                            <td>${source.name}</td>
                            <td>${source.description || '-'}</td>
                            <td>${source.event_count}</td>
                            <td>${source.created_at_formatted}</td>
                            <td>${source.updated_at_formatted}</td>
                            <td class="actions">
                                <button class="edit-btn" data-id="${source.id}" data-name="${source.name}" data-description="${source.description || ''}">编辑</button>
                            </td>
                        </tr>
                    `;
                });
                
                html += `
                        </tbody>
                    </table>
                `;
                
                document.getElementById('sourcesList').innerHTML = html;
                
                // 添加编辑按钮事件监听
                document.querySelectorAll('.edit-btn').forEach(button => {
                    button.addEventListener('click', function() {
                        const id = this.getAttribute('data-id');
                        const name = this.getAttribute('data-name');
                        const description = this.getAttribute('data-description');
                        
                        showEditForm(id, name, description);
                    });
                });
            }
            
            // 显示编辑表单
            function showEditForm(id, name, description) {
                document.getElementById('editSourceId').value = id;
                document.getElementById('editSourceName').value = name;
                document.getElementById('editSourceDescription').value = description;
                
                editSourceForm.style.display = 'block';
                selectSourcePrompt.style.display = 'none';
            }
            
            // 隐藏编辑表单
            function hideEditForm() {
                editSourceForm.style.display = 'none';
                selectSourcePrompt.style.display = 'block';
                editSourceForm.reset();
            }
        });
    </script>
</body>
</html>